#include "../Headers/dis_img_pro.h"
extern pthread_mutex_t  db_mutex;
int callback(void *para, int f_num, char **f_value, char **f_name)
{
    //*(int *)para = 1;
    int *p = (int *)para;
    *p = 1;
    return 0; // 如果不返回0表示错误
}

sqlite3 *datebase_open()
{
    sqlite3 *db = NULL;
    int ret = sqlite3_open("server.db", &db);
    ERROR_CHECK_SQL(ret, 0, "open", db);
    char * create_table = "create table if not exists userinfo(uname char(32) PRIMARY KEY,upasswd char(32))";
    ret = sqlite3_exec(db, create_table, NULL, NULL, NULL);
    ERROR_CHECK_SQL(ret, 0, "sql_create_table", db);
    return db;
}
void cleanFunc_db(void *arg)
{
    pthread_mutex_unlock(&db_mutex); 
}
int sql_table_val_create(int net_fd)
{
    char *name;
    char *passwd;
    char buf[1024];
    char sql[2048];
    recv(net_fd, buf, 1024, 0);
    int offset = strlen(buf);
    name = buf;
    passwd = buf + offset;
    puts(passwd);
    pthread_mutex_lock(&db_mutex);
    pthread_cleanup_push(cleanFunc_db, NULL);
    sqlite3 *db = datebase_open();
    sprintf(sql, "insert into userinfo values('%s', '%s');",name, passwd);
    if (0 != sqlite3_exec(db, sql, NULL, NULL, NULL))
    {
        bzero(name,32);
        strcpy(name, REG_FAILED);
        send(net_fd, name, 32, 0);
        return -1;
    }
    pthread_cleanup_pop(1);
    bzero(name,32);
    strcpy(name, REG_SUCCESS);
    send(net_fd, name, 32, 0);
    
}
int sql_table_val_delete(int net_fd)
{
}
int sql_table_val_alter(int net_fd)
{
}
int sql_table_val_select(int net_fd)
{
    char *name;
    char *passwd;
    char buf[1024];
    char sql[2048];
    recv(net_fd, buf, 1024, 0);
    puts(buf);
    int offset = strlen(buf);
    name = buf;
    passwd = buf + offset;
    puts(passwd);
    pthread_mutex_lock(&db_mutex);
    pthread_cleanup_push(cleanFunc_db, NULL);
    sqlite3 *db = datebase_open();   
    sprintf(sql, "select *from userinfo where uname = '%s' and upasswd = '%s';", name, passwd);
    puts(sql);
    int status = 0;
    if (0 != sqlite3_exec(db, sql, callback, &status, NULL))
    {
        bzero(name,32);
        strcpy(name, LOG_FAILED);
        send(net_fd, name, 32, 0);
        puts("1");
         puts(name);
        return -1;
    }
   
    if (status == 0)
    {
         bzero(name,32);
        strcpy(name, LOG_FAILED);
        send(net_fd, name, 32, 0);
         puts(name);
        return -1;
    }
    pthread_cleanup_pop(1);
    bzero(name,32);
    strcpy(name, LOG_SUCCESS);
    send(net_fd, name, 32, 0);
    puts(name);
   
}
